package com.xrf;

import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.graphics.Color;
import android.graphics.Typeface;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.EditText;
import androidx.appcompat.app.AlertDialog;
import androidx.core.content.ContextCompat;
import androidx.recyclerview.widget.LinearLayoutManager;
import com.esri.arcgisruntime.geometry.Geometry;
import com.esri.arcgisruntime.geometry.Point;
import com.esri.arcgisruntime.mapping.view.Graphic;
import com.esri.arcgisruntime.symbology.SimpleFillSymbol;
import com.esri.arcgisruntime.symbology.SimpleLineSymbol;
import com.esri.arcgisruntime.symbology.SimpleMarkerSymbol;
import com.example.mobilemap.R;
import com.example.mobilemap.Utility.ConstValue;
import com.example.mobilemap.Utility.GlobalValues;
import com.example.mobilemap.Utility.MapUtil;
import com.example.mobilemap.dialog.ListView.SlideGeoFileAdapter;
import com.yanzhenjie.recyclerview.OnItemClickListener;
import com.yanzhenjie.recyclerview.OnItemMenuClickListener;
import com.yanzhenjie.recyclerview.SwipeMenu;
import com.yanzhenjie.recyclerview.SwipeMenuBridge;
import com.yanzhenjie.recyclerview.SwipeMenuCreator;
import com.yanzhenjie.recyclerview.SwipeMenuItem;
import com.yanzhenjie.recyclerview.SwipeRecyclerView;
import com.yanzhenjie.recyclerview.widget.DefaultItemDecoration;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class GeometryFileDlg extends Dialog {
    @BindView(R.id.recyclerview_geometry_files)
    SwipeRecyclerView mRecyclerView;
    
    private Context context;
    private List<Object> mDataList;
    private SlideGeoFileAdapter mAdapter;
    
    public GeometryFileDlg(Context context) {
        super(context, R.style.MyBaseDialog);
        this.context = context;
        
        LayoutInflater inflater = LayoutInflater.from(context);
        View view = inflater.inflate(R.layout.dlg_geometry_files, null);
        setContentView(view);
        ButterKnife.bind(this);
        
        mAdapter = new SlideGeoFileAdapter(context);
        
        mRecyclerView.setSwipeMenuCreator(swipeMenuCreator);
        mRecyclerView.setOnItemMenuClickListener(mMenuItemClickListener);
        
        mRecyclerView.setLayoutManager(new LinearLayoutManager(context));
        mRecyclerView.addItemDecoration(new DefaultItemDecoration(
                ContextCompat.getColor(context, R.color.greyColor)));
        mRecyclerView.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(View view, int adapterPosition) {
                listViewItemClick(adapterPosition);
            }
        });
        
        initGeoFiles();
    }
    
    @OnClick(R.id.btn_geometryfiles_return)
    public void btnReturn() {
        this.dismiss();
    }
    
    void initGeoFiles() {
        List<String> list =
                GlobalValues.getInstance().getFilesName(
                        GlobalValues.getInstance().getAppFilePath()
                );
        mDataList = new ArrayList<Object>();
        
        for (String str : list) {
            mDataList.add(str);
        }
        
        if (list.size() > 0) {
            mRecyclerView.setAdapter(mAdapter);
            mAdapter.notifyDataSetChanged(mDataList);
        }
    }
    
    private void listViewItemClick(int pos) {
        byte[] data =
                GlobalValues.getInstance().readGeoFile(mDataList.get(pos).toString());
        List<Point> listPts;
        Geometry drawGeometry = null;
        
        switch (GlobalValues.getInstance().getDrawTypeByFilename(mDataList.get(pos).toString())) {
            case Draw_Point:
                listPts = GlobalValues.getInstance().getPtListFromBytes(data);
                MapUtil.getInstance().clearPointList();
                for (Point pt : listPts) {
                    MapUtil.getInstance().addPointMarker(pt);
                    MapUtil.getInstance().addPointToList(pt);
                }
                MapUtil.getInstance().setExtentByGeomtry();
                break;
            case Draw_Line:
                listPts = GlobalValues.getInstance().getPtListFromBytes(data);
                MapUtil.getInstance().clearPointList();
                for (Point pt : listPts) {
                    MapUtil.getInstance().addPointToList(pt);
                }
                MapUtil.getInstance().addLineMarker();
                MapUtil.getInstance().setExtentByGeomtry();
                break;
            case Draw_Polygon:
                listPts = GlobalValues.getInstance().getPtListFromBytes(data);
                for (Point pt : listPts) {
                    MapUtil.getInstance().addPointToList(pt);
                }
                MapUtil.getInstance().addGeometryMarker();
                MapUtil.getInstance().setExtentByGeomtry();
                break;
            case Draw_Hand_Point:
                SimpleMarkerSymbol simpleMarkerSymbol =
                        new SimpleMarkerSymbol(SimpleMarkerSymbol.Style.CIRCLE, Color.RED, 6);
                drawGeometry = MapUtil.getInstance().getGeometryFromJSON(new String(data));
                MapUtil.getInstance().clearGeoGraphics();
                MapUtil.getInstance().addGraphicsToOverlay(new Graphic(drawGeometry, simpleMarkerSymbol));
                MapUtil.getInstance().setExtentByGeomtry(drawGeometry);
                break;
            case Draw_Hand_Line:
                SimpleLineSymbol lineSymbol =
                        new SimpleLineSymbol(SimpleLineSymbol.Style.DASH, Color.YELLOW, 2);
                drawGeometry = MapUtil.getInstance().getGeometryFromJSON(new String(data));
                MapUtil.getInstance().clearGeoGraphics();
                MapUtil.getInstance().addGraphicsToOverlay(new Graphic(drawGeometry, lineSymbol));
                MapUtil.getInstance().setExtentByGeomtry(drawGeometry);
                break;
            case Draw_Hand_Polygon:
                SimpleLineSymbol outlineSymbol =
                        new SimpleLineSymbol(SimpleLineSymbol.Style.DASH, Color.YELLOW, 1);
                SimpleFillSymbol fillSymbol =
                        new SimpleFillSymbol(SimpleFillSymbol.Style.SOLID,
                                Color.parseColor("#66FF0000"),
                                outlineSymbol);
                drawGeometry = MapUtil.getInstance().getGeometryFromJSON(new String(data));
                MapUtil.getInstance().clearGeoGraphics();
                MapUtil.getInstance().addGraphicsToOverlay(new Graphic(drawGeometry, fillSymbol));
                MapUtil.getInstance().setExtentByGeomtry(drawGeometry);
                break;
            default:
                GlobalValues.getInstance().messageToast("Unsupported file type");
                return;
        }
        
        GlobalValues.getInstance().messageToast("File loaded successfully");
        this.dismiss();
    }
    
    private SwipeMenuCreator swipeMenuCreator = new SwipeMenuCreator() {
        @Override
        public void onCreateMenu(SwipeMenu leftMenu, SwipeMenu rightMenu, int position) {
            int height = ViewGroup.LayoutParams.MATCH_PARENT;
            SwipeMenuItem addItem = new SwipeMenuItem(context)
                    .setBackground(R.drawable.my_base_control_bg)
                    .setText("Rename")
                    .setTextSize(16)
                    .setTextColorResource(R.color.blue)
                    .setTextTypeface(Typeface.DEFAULT_BOLD)
                    .setWidth(GlobalValues.getInstance().getMainActivityWidth() / 6)
                    .setHeight(height);
            rightMenu.addMenuItem(addItem);
            
            SwipeMenuItem deleteItem = new SwipeMenuItem(context)
                    .setBackground(R.drawable.my_base_control_bg)
                    .setText("Delete")
                    .setTextSize(16)
                    .setTextColorResource(R.color.attach_red)
                    .setTextTypeface(Typeface.DEFAULT_BOLD)
                    .setWidth(GlobalValues.getInstance().getMainActivityWidth() / 6)
                    .setHeight(height);
            rightMenu.addMenuItem(deleteItem);
        }
    };
    
    private OnItemMenuClickListener mMenuItemClickListener = new OnItemMenuClickListener() {
        @Override
        public void onItemClick(SwipeMenuBridge menuBridge, int adapterPosition) {
            menuBridge.closeMenu();
            
            int direction = menuBridge.getDirection();
            int menuPosition = menuBridge.getPosition();
            
            if (direction == SwipeRecyclerView.RIGHT_DIRECTION) {
                String name = mDataList.get(adapterPosition).toString();
                switch (menuPosition) {
                    case 0:
                        final EditText editText = new EditText(context);
                        editText.setText(mDataList.get(adapterPosition).toString());
                        AlertDialog.Builder inputDialog =
                                new AlertDialog.Builder(context);
                        inputDialog.setTitle("Rename").setView(editText);
                        inputDialog.setPositiveButton("OK",
                                new DialogInterface.OnClickListener() {
                                    @Override
                                    public void onClick(DialogInterface dialog, int which) {
                                        String ctx = editText.getText().toString();
                                        if(GlobalValues.getInstance().getDrawTypeByFilename(ctx) == ConstValue.DrawType.Draw_None){
                                            GlobalValues.getInstance().messageToast("Invalid file name!");
                                            return;
                                        }
                                        if (GlobalValues.getInstance().renameFile(name, ctx)) {
                                            Collections.replaceAll(mDataList, name, ctx);
                                            mAdapter.notifyDataSetChanged(mDataList);
                                        }
                                    }
                                }).show();
                        break;
                    case 1:
                        final AlertDialog.Builder normalDialog =
                                new AlertDialog.Builder(context);
                        normalDialog.setIcon(R.drawable.ico_delete_dlg);
                        normalDialog.setTitle("Confirm Delete");
                        normalDialog.setMessage("Are you sure to delete \"" + name + "\"?");
                        normalDialog.setPositiveButton("Delete",
                                new DialogInterface.OnClickListener() {
                                    @Override
                                    public void onClick(DialogInterface dialog, int which) {
                                        GlobalValues.getInstance().deleteGeoFile(name);
                                        mDataList.remove(adapterPosition);
                                        mAdapter.notifyDataSetChanged(mDataList);
                                    }
                                });
                        normalDialog.setNegativeButton("Cancel", null);
                        normalDialog.show();
                        break;
                    default:
                        break;
                }
            }
        }
    };
    
    public void showDlg() {
        WindowManager.LayoutParams lp = getWindow().getAttributes();
        if (lp == null)
            return;
        
        lp.width = (int) (GlobalValues.getInstance().getMainActivityWidth() * 0.7);
        lp.height = (int) (GlobalValues.getInstance().getMainActivityHeight() * 0.8);
        getWindow().setAttributes(lp);
        Log.d("admin", "GeometryFileDlg width: " + lp.width + "; height: " + lp.height);
        this.show();
    }
}